package com.quanyan.ic.protocol.server;

import com.quanyan.ic.common.spring.SpringUtil;
import com.quanyan.ic.protocol.NamedThreadFactory;
import com.quanyan.ic.protocol.codec.ICMessageDecoder;
import com.quanyan.ic.protocol.codec.ICMessageEncoder;
import com.quanyan.ic.protocol.server.handler.HandShakeRespHandler;
import com.quanyan.ic.protocol.server.handler.HeartBeatRespHandler;
import com.quanyan.ic.protocol.server.handler.LightCmdRespHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhuo.shi on 2017/5/23.
 */
public class LightServer {

    private static Logger logger = LoggerFactory.getLogger(LightServer.class);

    private static Map<String, Channel> sessionChannelMap = new ConcurrentHashMap<>();
    private Integer port;

    public void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup(0, new NamedThreadFactory("icp-server-boss", true));
        NioEventLoopGroup worker = new NioEventLoopGroup(0, new NamedThreadFactory("icp-server-worker", true));

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
//                        pipeline.addLast(new ProtobufVarint32FrameDecoder());       //半包处理
                        pipeline.addLast(new ICMessageDecoder(10240 * 1024, 0, 4));
//                        pipeline.addLast(new ProtobufDecoder(ICMessageProto.ICMessage.getDefaultInstance()));       //解码器(目标类)
//                        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());       //对协议的的消息头上加上一个长度为32的整形字段，用于标志这个消息的长度。
//                        pipeline.addLast(new ProtobufEncoder());        //给应答消息编码
                        pipeline.addLast(new ICMessageEncoder());
                        pipeline.addLast(new HandShakeRespHandler());   //握手处理
                        pipeline.addLast(new HeartBeatRespHandler());   //心跳处理
//                        pipeline.addLast(new LightCmdRespHandler());         //业务处理
                        pipeline.addLast((LightCmdRespHandler) SpringUtil.getBean("lightCmdRespHandler"));
                    }
                });
        try {
            ChannelFuture f = serverBootstrap.bind(port).sync();
            logger.info("Light server started on port(s): {} (tcp) ", port);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static Map<String, Channel> getSessionChannelMap() {
        return sessionChannelMap;
    }

    public Integer getPort() {
        if (port == null){
            port = 9262;
        }
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }
}
